package com.first.nell.launch

import android.annotation.SuppressLint
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.first.nell.ProjectApplication
import com.first.nell.ProjectConfig
import com.first.nell.R
import com.first.nell.base.BaseActivity
import com.first.nell.components.dialog.PermissionItem
import com.first.nell.components.dialog.PermissionsDialog
import com.first.nell.databinding.ActivityFirstNellLaunchBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.network.ApiUrl
import com.first.nell.utils.UsageCountryUtil
import com.first.nell.utils.UserStateUtil
import com.first.nell.utils.analytics.util.AnalyticsUtil


/** 启动页 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity : BaseActivity() {

    //布局binding
    private lateinit var mFirstNellActivityFirstNellBinding: ActivityFirstNellLaunchBinding

    //权限弹框
    private val mPermissionsDialog = PermissionsDialog()

    //启动viewModel
    private val mLaunchViewModel by lazy {
        ViewModelProvider(this)[LaunchViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mLaunchViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onFirstNellBindingFirstNellViewFirstNellTag(): String {
        return PageTagEnum.launch.name.uppercase()
    }

    override fun onFirstNellBindingFirstNellContentFirstNellView(): View {
        mFirstNellActivityFirstNellBinding =
            ActivityFirstNellLaunchBinding.inflate(layoutInflater)
        return mFirstNellActivityFirstNellBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onFirstNellContentFirstNellViewFirstNellBinded() {
        try {
            //单国才需要这样配置！！
            //初始化分析模块
            //AnalyticsUtil.init(ProjectApplication.instance)
            //初始化国家
            //onFirstNellInitFirstNellCountry()

            //查询时区回调
            mLaunchViewModel.onFirstNellFetchFirstNellGlobalFirstNellConfigFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { _ ->
                        //初始化分析模块
                        AnalyticsUtil.init(ProjectApplication.instance)

                        //初始化国家
                        onFirstNellInitFirstNellCountry()

                        //获取系统配置
                        mUserStateViewModel.fetchFirstNellSysFirstNellConfig()
                    }
                }
            }

            //查询app配置回调
            mUserStateViewModel.onFirstNellFetchFirstNellSysFirstNellConfigFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //查询权限
                    val permissionList = PermissionsDialog.getPermissionList(this@LaunchActivity)

                    //需要展示权限框
                    if (permissionList.isNotEmpty()) {
                        //设置权限数据
                        mPermissionsDialog.setPermissionList(permissionList)

                        //展示
                        mPermissionsDialog.setShowDiaog(supportFragmentManager)
                    } else {
                        //直接下一步流程
                        checkFirstNellNextFirstNellStepFirstNellFromFirstNellAllFirstNellPermissionsFirstNellGrant()
                    }
                }
            }

            //查询用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    startFirstNellToFirstNellNextFirstNellFromFirstNellPage(PageTagEnum.launch)
                }
            }

            //设置拒绝设备权限回调
            mPermissionsDialog.setPhoneSateDenyClickListener {
                finish()
            }

            //设置请求权限回调
            mPermissionsDialog.setStartRequestPermissionClickListener { permission ->
                if (permission == PermissionItem.TYPE_SMS) {
                    requestFirstNellSmsFirstNellPermission(permission)
                } else {
                    requestFirstNellPhoneStateFirstNellPermission(permission)
                }
            }

            //设置同意所有权限回调
            mPermissionsDialog.setAllRequestPermissionAgreeListener {
                //查询全局配置
                onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass()
            }

            //初始化版本信息
            mFirstNellActivityFirstNellBinding.textLaunchProductVersion.text = getString(
                R.string.first_nell_version_flag,
                "${ProjectConfig.NARSCASH_Version_NAME}(${ProjectConfig.NARSCASH_Version})"
            )

            //获取时区
            mLaunchViewModel.fetchFirstNellGlobalFirstNellConfig()

            //获取系统配置
            //mUserStateViewModel.fetchFirstNellSysFirstNellConfig()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()

        //获取时区
        //mLaunchViewModel.fetchFirstNellGlobalFirstNellConfig()


        //测试
        //startFirstNellToFirstNellIdentityCardFirstNellActivity()
    }

    override fun onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass() {
        checkFirstNellNextFirstNellStepFirstNellFromFirstNellAllFirstNellPermissionsFirstNellGrant()
    }

    override fun onFirstNellPermissionsFirstNellRequestFirstNellPhoneStateFirstNellPass() {
        onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass()
    }

    override fun onFirstNellPermissionsFirstNellRequestFirstNellSMSFirstNellPass(realAgree: Boolean) {
        mPermissionsDialog.setPermissionResult(PermissionItem.TYPE_SMS, realAgree)
    }

    /** 处理同意所有权限返回后，下一步应该怎样走 */
    private fun checkFirstNellNextFirstNellStepFirstNellFromFirstNellAllFirstNellPermissionsFirstNellGrant() {
        //查询用户状态
        if (UserStateUtil.isFirstNellDidFirstNellLogin()) {
            //判断用户类型
            //获取用户状态
            mUserStateViewModel.fetchFirstNellUserFirstNellState()

//            if (UserStateUtil.isFirstNellAdFirstNellSource()) {
//                //获取用户状态
//                mUserStateViewModel.fetchFirstNellUserFirstNellState()
//            } else {
//                //跳转记账软件首页
//                startFirstNellToFirstNellBillFirstNellRecordFirstNellHomeFirstNellPage()
//            }

            try {
                //保存s2s信息
                AnalyticsUtil.saveFirebaseAndFacebookS2SInfo()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            //去登录页
            startFirstNellToFirstNellLoginFirstNellActivity()
        }
    }

    /**
     * 初始化国家
     *
     * @param country 国家
     * @param path 转发路径
     */
    private fun onFirstNellInitFirstNellCountry() {
        val path = ApiUrl.BASE_PATH
        println("处理切换国家回调-path:$path")
        //路径前加/
        val specPath = path.toFirstNellPathFirstNellFormat()

        //更新用户管理中的地区与请求路径
        UsageCountryUtil.saveFirstNellApiFirstNellPath(specPath)

        //更新设备回传地址
        AnalyticsUtil.initDevice(ProjectApplication.instance)
    }
}